<script>
//  function mod(which, arg) {
//    var sn = $(which).siblings('#sn').val();
//    console.log(sn);
//    var amount = $(which).siblings('#amount').val();
//    var openid = sessionStorage.getItem('openid');
//    console.log(sn, amount);
//    $.ajax({
//      url: '/users/cart/',
//      type: 'PUT',
//      data: {
//        sn: sn,
//        amount: amount,
//        openid: openid
//      },
//      success: function(result){
//        console.log(result);
//        if (result == 'ok'){
//            mui.toast('操作成功');
//            calculate_all();
//        }
//      }
//    })
//  }
  function plus(which) {
    var num = Number($(which).siblings('#amount').val());
    console.log('number is:',num);
    $(which).siblings('#amount').val(num+1);
    calculate_all();
  };

  function minus(which) {
    var num = Number($(which).siblings('#amount').val());
    if (num-1 < 0) {
      $(which).siblings('#amount').val(0);
    } else {
      $(which).siblings('#amount').val(num-1);
    }
    calculate_all();
  }

  function delete_from_cart(sn) {
    console.log(sn);
    $.ajax({
      url: '/users/cart/'+sn+'/?openid='+sessionStorage.getItem('openid'),
      type: 'DELETE',
      data: {
      },
      success: function (call) {
        if (call == 'success'){
            get_cart();
            mui.toast('删除成功!');
        }
      }
    })
  }

  function get_cart() {
    var openid = sessionStorage.getItem('openid');
    $.get('/api/user/'+openid+'/cart/', function (call) {
      var html = '';
      console.log(call);
      if (call.length == 0) {
          html = '<p>do it!</p>';
      } else {
        for (var i=0; i<call.length; i++) {
          var cny = Number(call[i].product.msrp)*Number(sessionStorage.getItem('rate'));
          html += '<li><div class="shop-info"><input type="checkbox" class="check goods-check goodsCheck" name="product_check_box" onclick="calculate_all()"><div class="shop-info-img"><a href="#"><img src="http://auewe.oss-ap-southeast-2.aliyuncs.com/products/' + call[i].product.sn + '_thumb.jpeg" /></a></div>' +
            '<div class="shop-info-text"><h4>' + call[i].product.brand + '&nbsp;'+call[i].product.name+'</h4><div class="shop-brief"><span>'+call[i].product.pinyin+'</span><span>型号：'+call[i].product.model+'</span></div><div class="shop-price"><div class="shop-pices">$<b class="price">'+call[i].product.msrp+'</b> ¥<b>'+cny.toFixed(2)+'</b>'+
            '</div><div class="mui-numbox" data-numbox-min="1"><button class="mui-btn mui-numbox-btn-minus" type="button" onclick="minus(this)">-</button><input class="mui-numbox-input" id="amount" type="number" border="0" value="'+call[i].amount+'" /><input type="hidden" value="'+call[i].product.sn+'" id="sn">'+
            '<button class="mui-btn mui-numbox-btn-plus" type="button" onclick="plus(this)">+</button></div></div></div></div></li>';
        }
      }
      $('form>ul').html(html);
    })
  }
</script>
<style>
  .icon-delete{
    margin-left: 75%;
  }
</style>
<header class="mui-bar mui-bar-nav header">
  <h1 class="mui-title">购物车</h1>
  <div class="mui-icon mui-pull-right" id="mod-cart"><span style="font-size: initial">删除</span></div>
</header>
<div class="mui-content">
  <div class="shopping">
    <div class="shop-group-item">
      <form>
      <ul>

      </ul>
      </form>
    </div>
  </div>
</div>
<!--底部导航-->
<div class="jl"></div>
<div class="payment-bar">
  <div class="all-checkbox"><input type="checkbox" class="check goods-check" id="AllCheck">全选</div>
  <div class="shop-total">
    <strong>总价：<i class="total" id="AllTotal">0.00</i></strong>
    <!--<span>减免：123.00</span>-->
  </div>
  <div class="settlement">结算</div>
</div>
<nav class="mui-bar mui-bar-tab">
  <a class="mui-tab-item" href="/">
    <span class="mui-icon "><i class="iconfont">&#xe601;</i></span>
    <span class="mui-tab-label">首页</span>
  </a>
  <a class="mui-tab-item" href="/list">
    <span class="mui-icon mui-icon-list"></span>
    <span class="mui-tab-label">列表</span>
  </a>
  <a class="mui-tab-item mui-active" href="/cart">
    <span class="mui-icon"><i class="iconfont">&#xe600;</i></span>
    <span class="mui-tab-label">购物车</span>
  </a>
  <a class="mui-tab-item" href="/account">
    <span class="mui-icon"><i class="iconfont">&#xe654;</i></span>
    <span class="mui-tab-label">我的</span>
  </a>
</nav>
<script>
  $(function () {
    get_cart();
  })
  mui('body').on('tap','a',function(){
    window.top.location.href=this.href;
  });
  $('#mod-cart').click(function () {
    $('.goodsCheck').each(function () {
      if($(this).prop('checked')) {
          var sn = $(this).parent().find('#sn').val();
          delete_from_cart(sn);
      }
    })
  })
  $('.settlement').click(function () {
    var total = Number($('.price').text());
    var input_list = $('.goodsCheck');
    var _slice = Array.prototype.slice;
    //var products = [];
    var products_list = _slice.call(input_list).map(function (x) {
      if (x.checked){
          return {
              sn: $(x).parent().find('#sn').val(),
              amount: $(x).parent().find('#amount').val()
          };
      }
      return null;
    }).filter(function (x) {
      return x !== null;
    });
    console.log(products_list)
    var reqBody = {
      openid: sessionStorage.getItem('openid'),
      status: 'pending',
      products: JSON.stringify(products_list),
      total: total,
    };
    console.log(reqBody);
    $.post('/orders/', reqBody, function (call, stat) {
        console.log(call, stat);
        if (stat == 'success') {
          window.location.href = '/user/order/address/?order_id='+call;
          console.log(call);
        }
    });
  })
  function calculate_price(elem) {

//    var $elem = $(elem);
    var shop_info = $('.shop-info');
//    console.log(shop_info, typeof shop_info, shop_info instanceof Array);
    var map = Array.prototype.map;

    var _slice = Array.prototype.slice;

    var ret = _slice.call(shop_info).map(function(x){
        return [$(x).find('.goodsCheck')[0].checked, Number($(x).find('.price').text()), $(x).find('#amount').val()];
    }).map(function(checked_price_amount){
        var checked = checked_price_amount[0];
        var price = checked_price_amount[1];
        var amount = checked_price_amount[2];
        return checked ? (price * amount) : 0.0
    }).reduce(function(acc, cur){
        return acc + cur;
    }, 0);

    console.log('ret', ret);
    $('#AllTotal').text(ret);
    return ret;
  }
  $('#AllCheck').change(function () {
    if ($(this)[0].checked) {
        $('.shop-group-item .goodsCheck').each(function (i, elem) {
          elem.checked = true;
          elem.onclick.call(elem);
        })
    } else {
        $('.shop-group-item .goodsCheck').each(function (i, elem) {
          elem.checked = false;
          elem.onclick.call(elem);
        })
    }

  })

  function calculate_all(){
      var total = 0;
      $('.goodsCheck').each(function(){
          if ($(this).prop('checked')) {
              var price = $(this).parent('.shop-info').find('.price').text();
              var amount = $(this).parent('.shop-info').find('#amount').val();
              console.log('price:',price,'amount:',amount);
              total += Number(price)*Number(amount);
          }
      })
      var rate = sessionStorage.getItem('rate');
      $('#AllTotal').text('$'+total+' ¥'+Number(total*rate).toFixed(2));
      select_all();
  }

  function select_all() {
    var product_count = Number('<%= data.length%>');
    console.log('count:',product_count);
    var checked = 0;
    $('.goodsCheck').each(function () {
      if ($(this).prop('checked')) {
        checked += 1;
      }
    });
    if (checked === product_count) {
      $('#AllCheck')[0].checked = true;
    } else {
      $('#AllCheck')[0].checked = false;
    }
  }
</script>


